import styles from './index.module.scss'
import { RootState } from '@/store'
import { channelAdd, channelDel, getAllChannels, getChannels } from '@/store/action/channel'
import { Popup, Tabs } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import Icon from '@/components/Icon'
import classNames from 'classnames'
import _ from 'lodash'
import { Channel } from '@/store/reducer/channel'
import history from '@/utils/history'
export default function Channels() {

  const dispatch = useDispatch()

  useEffect(() => {
    // 获取用户频道（或者是没有登录的默认频道）
    dispatch(getChannels())
    // 获取所有的频道
    dispatch(getAllChannels())
  }, [dispatch])

  const { list, alllist, sroolNum,activeId } = useSelector((state: RootState) => state.channel)

  // 计算出剩余的频道
  // const leftList = alllist.filter(v => {
  //   const obj = list.find(p => p.id === v.id)
  //   return obj ? false : true
  // })
  // 使用 lodash 计算剩余频道
  const leftList = _.differenceBy(alllist, list, 'id')

  // -------------左边弹出层
  const [popupShow, setPopupShow] = useState(false)
  // 控制我的频道和页面list的高亮
  const [channelsId, setChannelsId] = useState(0)

  useEffect(() => {
    setChannelsId(activeId)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 点击编辑和完成
  const [editDone, setEditDone] = useState(false)

  // 点击剩余的频道
  const handlAdd = (item: Channel) => {
    dispatch(channelAdd(item))
  }

  useEffect(() => {
    dispatch({ type: 'channel/setSroolNum', payload: document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop })
    // window.scrollTo({ top: sroolNum[channelsId] ? sroolNum[channelsId] : 0, behavior: 'smooth' })
    setTimeout(() => {
      
      window.scrollTo({ top: sroolNum[channelsId] ? sroolNum[channelsId] : 0 })
    }, 200);

    dispatch({ type: 'channel/setActiveId', payload: channelsId })

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channelsId, dispatch])

  return (
    <div className={styles.root}>
      <Tabs activeKey={String(channelsId)} onChange={((val) => setChannelsId(Number(val)))}>
        {list.map((item) => <Tabs.Tab title={item.name} key={item.id} />)}
      </Tabs>
      <div className='iconBox'>
        <Icon type='iconbtn_search' onClick={() => history.push('/Search')} />
        <Icon type='iconbtn_channel' onClick={() => setPopupShow(true)} />
      </div>
      {/* 编辑频道弹出层 */}
      <Popup visible={popupShow} position='left' bodyClassName={styles.channelPopup}>
        {/* 顶部栏：带关闭按钮 */}
        <div className='channel-header'>
          <Icon type='iconbtn_channel_close' onClick={() => setPopupShow(false)} />
        </div>

        {/* 频道列表 */}
        <div className='channel-content'>
          {/* 当前已选择的频道列表 */}
          <div className={classNames('channel-item', editDone ? 'edit' : '')}>
            <div className='channel-item-header'>
              <span className='channel-item-title'>我的频道</span>
              <span className='channel-item-title-extra'>点击进入频道</span>
              <span className='channel-item-edit' onClick={() => setEditDone(!editDone)}>{editDone ? '完成' : '编辑'}</span>
            </div>

            <div className='channel-list'>
              {/* 用户频道列表 list */}
              {list.map((item) => (
                <span
                  key={item.id}
                  onClick={() => {
                    if (editDone) return
                    setPopupShow(false)
                    setChannelsId(item.id)
                  }}
                  className={classNames('channel-list-item', item.id === channelsId ? 'active' : '')}>
                  {item.name}
                  <Icon type='iconbtn_tag_close' onClick={() => dispatch(channelDel(item.id))} />
                </span>
              ))}

              {/* 推荐的频道列表 */}
              <div className='channel-item'>
                <div className='channel-item-header'>
                  <span className='channel-item-title'>频道推荐</span>
                  <span className='channel-item-title-extra'>点击添加频道</span>
                </div>
                <div className='channel-list'>
                  {/* 剩下的频道 leftList */}
                  {leftList.length === 0 ?
                    '木有拉...'
                    :
                    <>
                      {leftList.map(item => (
                        <span onClick={() => handlAdd(item)} key={item.id} className='channel-list-item'> + {item.name}</span>
                      ))}
                    </>
                  }
                </div>
              </div>

            </div>
          </div>
        </div>
      </Popup>
    </div>
  )

}

